<?php
// +----------------------------------------------------------------------
// | zhanshop-clouds / BridgeServerProxy.php    [ 2025/1/6 14:22 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2011~2025 zhangqiquan All rights reserved.
// +----------------------------------------------------------------------
// | Author: zhangqiquan <768617998@qq.com>
// +----------------------------------------------------------------------
declare (strict_types=1);

namespace extend\bridgeserv;

use extend\bridgeserv\client\HttpClient;
use extend\bridgeserv\client\Socks5Client;
use Swoole\Server;

class BridgeServerProxy
{
    /**
     * @var HttpClient[]
     */
    public $proxyHttpClients = [];

    /**
     * @var Socks5Client[]
     */
    public $proxySocks5Clients = [];

    /**
     * http消息
     * @param Server $server
     * @param int $fd
     * @param string $data
     * @return void
     */
    public function httpMessage(mixed $server, int $fd, string $data)
    {
        $httpClient = $this->proxyHttpClients[$fd] ?? null;
        if($httpClient == false){
            $httpClient = new HttpClient($this);
            if($httpClient->connect($server, $fd, $data)){
                $this->proxyHttpClients[$fd] = $httpClient;
            }
        }else{
            $httpClient->send($server, $fd, $data); // 给代理目标发送消息
        }
    }
    /**
     * http关闭消息
     * @param $server
     * @param $fd
     * @return void
     */
    public function httpClose($server, $fd)
    {
        $httpClient = $this->proxyHttpClients[$fd] ?? null;
        if($httpClient != false){
            unset($this->proxyHttpClients[$fd]);
            $httpClient->close($server, $fd); // 给代理目标发送消息
        }
    }
    /**
     * socks5消息
     * @param Server $server
     * @param int $fd
     * @param string $data
     * @return void
     */
    public function socks5Message(mixed $server, int $fd, string $data)
    {
        $socks5Client = $this->proxySocks5Clients[$fd] ?? null;
        if($socks5Client == false){
            $socks5Client = new Socks5Client($this);
            if($socks5Client->init($server, $fd, $data)){
                $this->proxySocks5Clients[$fd] = $socks5Client;
            }
        }else{
            $method = $socks5Client->method;
            $socks5Client->$method($server, $fd, $data);
        }
    }

    /**
     * socks5关闭消息
     * @param $server
     * @param $fd
     * @return void
     */
    public function socks5Close($server, $fd)
    {
        $socks5Client = $this->proxySocks5Clients[$fd] ?? null;
        if($socks5Client){
            unset($this->proxySocks5Clients[$fd]);
            $socks5Client->close($server, $fd); // 给代理目标发送消息
        }
    }
}